package org.example.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import jakarta.annotation.Resource;
import org.example.dao.comment.CommentMapper;
import org.example.dao.goods.GoodsMapper;
import org.example.dao.ordergoods.OrderGoodsMapper;
import org.example.entity.Comment;
import org.example.entity.OrderGoods;
import org.example.entity.PageBean;
import org.example.service.CommentService;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class CommentServiceImpl implements CommentService {

    @Resource
    private CommentMapper commentMapper;

    @Resource
    private OrderGoodsMapper orderGoodsMapper;


    @Resource
    private GoodsMapper goodsMapper;
    /**
     * 新增评论
     * */
    @Override
    public boolean addComment(String openId,Integer orderId,String commentText) {
        boolean flag = false;
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//注意月和小时的格式为两个大写字母
        Date date = new Date();//获得当前时间
        String birthday = df.format(date);
        List<OrderGoods> goodsList = orderGoodsMapper.getOrderGoodsByOrderId(orderId);
        Comment comment = new Comment();
        comment.setCreateTime(birthday);
        comment.setOpenId(openId);
        comment.setCommentText(commentText);
        for (int i = 0; i < goodsList.size(); i++) {
            comment.setGoodsId(goodsList.get(i).getGoodsId());
            flag = commentMapper.addComment(comment);
        }
        return flag;
    }



    /**
     * 删除评论
     * */
    @Override
    public boolean deleteComment(Integer commentId) {
        return commentMapper.deleteComment(commentId);
    }

    /**
     * 用户获取自己的评论列表
     * */
    @Override
    public List<Comment> getUsersComment(String openId) {
        return commentMapper.getUsersComment(openId);
    }


    /**
     * 获取菜品的评论*/
    @Override
    public List<Comment> getGoodsComment(Integer goodsId) {
        return commentMapper.getGoodsComment(goodsId);
    }

    /**
     * 按需求查找
     * */
    @Override
    public PageBean<Comment> getCommentListByReason(Integer pageSize, Integer page, String commentIdBegin, String commentIdEnd, String commentText, String goodsId, String beginTime, String endTime) {
        PageHelper.startPage(page,pageSize);
        List<Comment> list = commentMapper.listByReason(commentIdBegin,commentIdEnd,commentText,goodsId,beginTime,endTime);

        Page<Comment> p = (Page<Comment>) list;

        long total = p.getTotal();
        list = p.getResult();

        for (int i = 0 ; i < list.size() ; i++) {
            list.get(i).setGoodsName(goodsMapper.getGoodsNameById(list.get(i).getGoodsId()));
        }
        return new PageBean<Comment>(total,list);
    }
}
